package com.gln.bloger.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.compass.core.Compass;
import org.compass.core.CompassHit;
import org.compass.core.support.search.CompassSearchCommand;
import org.compass.core.support.search.CompassSearchHelper;
import org.compass.core.support.search.CompassSearchResults;
import org.compass.gps.CompassGps;

import com.gln.bloger.compass.SearchResultWapper;
import com.gln.bloger.constant.Constant;
import com.gln.bloger.service.SearchService;

public class SearchServiceImpl implements SearchService {

    private Compass compass;
	
	private CompassGps compassGps;
	
	public CompassGps getCompassGps() {
		return compassGps;
	}
	public void setCompassGps(CompassGps compassGps) {
		this.compassGps = compassGps;
	}
	/**
	 * search by query
	 * @param query
	 * @param currentPage
	 * @return
	 */
	public SearchResultWapper search(String query, int currentPage){
		SearchResultWapper result = new SearchResultWapper();
		
		CompassSearchCommand searchCommand = new CompassSearchCommand();
		CompassSearchHelper searchHelper = new CompassSearchHelper(compass, Constant.PAGE_SIZE);
		searchCommand.setPage(new Integer(currentPage-1));
		searchCommand.setQuery(query);
		CompassSearchResults searchResults = searchHelper.search(searchCommand);
		List<CompassHit> hits = new ArrayList<CompassHit>();
		//copy to list
		for(CompassHit hit : searchResults.getHits()){
			hits.add(hit);
		}
		result.setHits(hits);
		result.setPages(searchResults.getPages());
		result.setTotalHits(searchResults.getTotalHits());
		result.setSearchTime(searchResults.getSearchTime());
		return result;
	}
	/**
	 * index
	 * @return
	 */
	public long  index(){
		long time = System.currentTimeMillis();
		getCompassGps().index();
		long elapsedTime = System.currentTimeMillis()-time;
		return elapsedTime;
	}
	public Compass getCompass() {
		return compass;
	}
	public void setCompass(Compass compass) {
		this.compass = compass;
	}

}
